import { Component, OnInit } from '@angular/core';
import getData_ajax from '../../../common/utils/getData_ajax';
import config from '../../../common/utils/baseUrl';
import { NzModalRef, NzModalService } from 'ng-zorro-antd';
import { ActivatedRoute, NavigationEnd, Router } from '@angular/router';
import promise from '../../../common/utils/promise';

@Component({
  selector: 'app-article-list',
  templateUrl: './article-list.component.html',
  styleUrls: ['./article-list.component.scss'],
})
export class ArticleListComponent implements OnInit {
  confirmModal: NzModalRef; // For testing by now
  public isSpinning: any = true; // 加载状态
  public ariticeData: any = []; // 文章数据
  constructor(private modal: NzModalService, private router: Router,
              private activatedRoute: ActivatedRoute) {
  }

  ngOnInit() {
    // 调回本页面，刷新页面
    this.router.events.subscribe((item) => {
      if (item instanceof NavigationEnd && item.url.indexOf('article-management/article-list') > -1 && this.activatedRoute.snapshot.queryParams.reload) {
        this.getData();
      }
    });
    this.getData();
  }

  /**
   * 拉取数据
   */
  getData() {
    promise.commonRequest.post('', '/api/articleService/getArticeData').then((data) => {
      // @ts-ignore
      if (data.isEffective) {
        // @ts-ignore
        this.ariticeData = data.result;
        this.isSpinning = false;
        console.log(this.ariticeData);
      } else {
        this.router.navigateByUrl('/passport/login');
        sessionStorage.setItem('previousUrl', window.location.pathname);
      }
    }).catch((error) => {
      if (!error.responseJSON.isEffective) {
        this.router.navigateByUrl('/passport/login');
        sessionStorage.setItem('previousUrl', window.location.pathname);
      }
    });
  }

  /**
   * 删除文章
   */
  delectArticleFunc(id) {
    this.modal.confirm({
      nzTitle: '确定？',
      nzContent: '<b>小哥哥，小姐姐，你确定要删除这个文章，删了就没有了.....</b>',
      nzOnOk: () =>
        promise.commonRequest.post({ id: id }, '/api/articleService/deleteAritice').then((data) => {
          // @ts-ignore
          if (data.isEffective) {
            // @ts-ignore
            this.modal.success({
              nzTitle: '成功！',
              nzContent: '小哥哥，小姐姐，你成功删除了这个文章......',
            });
            this.getData();
          } else {
            this.router.navigateByUrl('/passport/login');
            sessionStorage.setItem('previousUrl', window.location.pathname);
          }
        }).catch(error => {
          if (!error.responseJSON.isEffective) {
            this.router.navigateByUrl('/passport/login');
            sessionStorage.setItem('previousUrl', window.location.pathname);
          } else {
            this.modal.error({
              nzTitle: '失败！',
              nzContent: '小哥哥，小姐姐，待会再来删除这个文章吧......',
            });
          }
        }),
    });
  }
}
